package com.hwtx.form.domain.handle;

import com.hwtx.form.annotation.FormType;
import com.hwtx.form.domain.def.FormDef;
import com.hwtx.form.domain.repo.SysLogRepo;
import com.hwtx.form.dto.FormListQuery;
import io.geekidea.boot.framework.page.Paging;
import io.geekidea.boot.system.query.SysLogQuery;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import static com.hwtx.form.domain.FormConstants.LOG_FORM_HANDLE_NAME;

@FormType(LOG_FORM_HANDLE_NAME)
@Slf4j
public class LogFormHandle implements FormDataHandle {

    @Resource
    private SysLogRepo sysLogRepo;

    @Override
    public Paging<?> page(FormDef formDef, FormListQuery formListQuery) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysLogQuery sysLogQuery = new SysLogQuery();
        sysLogQuery.setPageIndex(formListQuery.getPageIndex());
        sysLogQuery.setPageSize(formListQuery.getPageSize());
        sysLogQuery.setKeyword(formListQuery.getKeyword());
        sysLogQuery.setOrderByAsc(formListQuery.getOrderByAsc());
        sysLogQuery.setOrderByColumn(formListQuery.getOrderByColumn());
        if (formListQuery.getSearchPostData().containsKey("logName")) {
            sysLogQuery.setLogName((String) formListQuery.getSearchPostData().get("logName"));
        }
        if (formListQuery.getSearchPostData().containsKey("createStartTime")) {
            try {
                sysLogQuery.setCreateStartTime(simpleDateFormat.parse((String) formListQuery.getSearchPostData().get("createStartTime")));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        if (formListQuery.getSearchPostData().containsKey("createEndTime")) {
            try {
                sysLogQuery.setCreateEndTime(simpleDateFormat.parse((String) formListQuery.getSearchPostData().get("createEndTime")));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        if (formListQuery.getSearchPostData().containsKey("userName")) {
            sysLogQuery.setUsername((String) formListQuery.getSearchPostData().get("userName"));
        }
        if (formListQuery.getSearchPostData().containsKey("requestUrl")) {
            sysLogQuery.setRequestUrl((String) formListQuery.getSearchPostData().get("requestUrl"));
        }
        return sysLogRepo.page(sysLogQuery);
    }
}
